import store from '@/store/index.js'


const host = 'http://hotel.test/api/v1'


/**
 * 刷新 Token
 */
const checkToken = async () => {
	const accessToken = store.getters.accessToken
	const accessTokenExpiredAt = store.getters.accessTokenExpiredAt
	
	if (accessToken && new Date().getTime() > accessTokenExpiredAt) {
		try {
			return store.dispatch('refreToken')
		} catch (err) {
			return store.dispatch('login')
		}
	}
}


// 普通请求
const authRequest = async (options = {}) => {
	await checkToken()

	options.header = {
		Authorization: 'Bearer ' + store.getters.accessToken
	}

  return await request(options, false)
}


/**
 * 网络请求
 */
const request = async (options = {}, showLoading = true) => {
	//await checkToken()

	if (showLoading) {
		uni.showLoading({
			title:'加载中...'
		})
	}
	
	let url = host + options.url
	
	return new Promise((resolve, reject)=>{
		uni.request({
			url,
			method: options.method || 'GET',
			data: options.data || {},
			header: options.header || {},
			success: res =>{
				if (res.statusCode >= 200 && res.statusCode < 300) {
					return resolve(res)
				}
				
				if (res.statusCode === 429) {
					wx.showModal({
						title: '提示',
						content: '请求太频繁，请稍后再试'
					})
				}

				if (res.statusCode === 500) {
					wx.showModal({
						title: '提示',
						content: '服务器错误，请联系管理员或重试'
					})
				}
				
				const error = {}
				error.res = res
				error.statusCode = res.statusCode
				return reject(error)
			},
			fail: err =>{
				return reject(err)
			},
			complete: com => {
				uni.hideLoading()
			}
		})
	})
}
	
	
export {
	request,
	authRequest
}